#include "usart3.h"
#include "utils.h"
#include "string.h"

#define Set_RE GPIO_SetBits(GPIOB, GPIO_Pin_1);
#define Clr_RE GPIO_ResetBits(GPIOB, GPIO_Pin_1);

#define Set_DE GPIO_SetBits(GPIOB, GPIO_Pin_0);
#define Clr_DE GPIO_ResetBits(GPIOB, GPIO_Pin_0);

void USART3_Config(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  USART_InitTypeDef USART_InitStructure;

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  USART_InitStructure.USART_BaudRate = 9600;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_Init(USART3, &USART_InitStructure);

  USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);

  USART_Cmd(USART3, ENABLE);
}

void RS485_SendBytes_U3(const uint8_t *bytes, int len)
{
  Set_DE;
  Set_RE;
  USART_SendBytes(USART3, bytes, len);
  Clr_DE;
  Clr_RE;
}

void RS485_SendByte_U3(uint8_t data)
{
  RS485_SendBytes_U3(&data, 1);
}

void RS485_SendString_U3(const char *str)
{
  RS485_SendBytes_U3((const uint8_t *)str, strlen(str));
}

void USART3_init(void)
{
  USART3_Config();
}

static uint8_t usart3_buffer[RS485_RX_BUFFER_SIZE_U3];
__IO int usart3_buffer_index = 0;
void RS485_Received_Byte_U3(uint8_t data)
{
    if (usart3_buffer_index == sizeof(usart3_buffer)) {
      usart3_buffer_index = 0;
    }
    usart3_buffer[usart3_buffer_index] = data;
    usart3_buffer_index += 1;
}

int RS485_Get_Reveived_Data_U3(uint8_t *buffer, int buffer_size)
{
  int i;
  int len;

  if (usart3_buffer_index < buffer_size) {
    len = usart3_buffer_index;
  } else {
    len = buffer_size;
  }
  for (i = 0; i < len; i++) {
    buffer[i] = usart3_buffer[i];
  }
  return len;
}

void RS485_Reset_Buffer_U3(void)
{
  usart3_buffer_index = 0;
}
